package org.ru.mse10.cvis.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.ru.mse10.cvis.util.security.BCrypt;

import edu.vt.middleware.password.CharacterRule;
import edu.vt.middleware.password.DigitCharacterRule;
import edu.vt.middleware.password.LowercaseCharacterRule;
import edu.vt.middleware.password.NonAlphanumericCharacterRule;
import edu.vt.middleware.password.PasswordGenerator;
import edu.vt.middleware.password.UppercaseCharacterRule;

/**
 * Contains commonly used utility methods. This class <strong>MUST NOT</strong>
 * contain any business logic.
 * 
 * @author yasko
 * 
 */
public class CommonUtil {

	/**
	 * Lookup service.
	 * 
	 * @param <S>
	 *            the generic type
	 * @param clazz
	 *            the clazz
	 * @return the s
	 * @throws NamingException
	 *             the naming exception
	 */
	@SuppressWarnings("unchecked")
	public static <S> S lookupService(Class<S> clazz) throws NamingException {
		InitialContext context = new InitialContext();
		String uri = "java:app/" + context.lookup("java:app/AppName") + "/"
				+ clazz.getSimpleName() + "!" + clazz.getName();
		return (S) context.lookup(uri);
	}

	/**
	 * Checks if is empty.
	 * 
	 * @param s
	 *            the s
	 * @return true, if is empty
	 */
	public static boolean isEmpty(String s) {
		return s == null || s.isEmpty();
	}

	/**
	 * Checks if is empty.
	 * 
	 * @param c
	 *            the c
	 * @return true, if is empty
	 */
	public static boolean isEmpty(Collection<?> c) {
		return c == null || c.isEmpty();
	}

	/**
	 * Checks if is empty.
	 * 
	 * @param o
	 *            the o
	 * @return true, if is empty
	 */
	public static boolean isEmpty(Object o) {
		return o == null;
	}

	/**
	 * Hash password.
	 * 
	 * @param password
	 *            the password
	 * @return the string
	 */
	public static String hashPassword(String password) {
		return BCrypt.hashpw(password, BCrypt.gensalt());
	}

	/**
	 * Generate password.
	 * 
	 * @return the string
	 */
	public static String generatePassword() {
		PasswordGenerator generator = new PasswordGenerator();
		List<CharacterRule> rules = new ArrayList<CharacterRule>();
		rules.add(new DigitCharacterRule(1));
		rules.add(new NonAlphanumericCharacterRule(1));
		rules.add(new UppercaseCharacterRule(1));
		rules.add(new LowercaseCharacterRule(1));
		return generator.generatePassword(((int) (Math.random() * 9) + 8),
				rules);
	}
}
